/*
 * @Author: wangtao
 * @Date: 2020-06-29 16:32:41
 * @LastEditors: zeki mini
 * @LastEditTime: 2021-04-13 16:45:53
 * @Description: file content
 */

import React, { Component } from 'react';
import {
  StyleSheet,
  View,
  Modal,
  Text,
  TouchableOpacity,
  PixelRatio,
  ScrollView,
  Image,
  TextInput,
  KeyboardAvoidingView,
  Keyboard,
  Switch,
} from 'react-native';
import DateTimePicker from 'react-native-modal-datetime-picker';
import Moment from 'moment';
import {
  mainBgColorLightGray,
  mainBgColorWhite,
  fontColorDeepRed,
  fontColorBlack,
  fontColorLightGray,
  fontColorCoffee,
  screenWidth,
  px2dp,
  screenHeight,
  splitLineColorLightGray,
  fontColorSecDeepGray,
  mainBgColorBlack,
  fontColorDeepGray,
  fontColorLightCoffee,
} from '../../../../../common/styles';
import { Button, DashLine, msg } from '../../../../../common';
import { iconUpdate } from '../../../../../image';
import {
  allPackageType,
  findPackageTypeByGoodsTypeId,
  fetchUnitList,
} from '../../../../../api/source-release';
import SelectItem from './select-item';

const { Submit } = Button;

export default class SourceInfo extends Component {
  constructor(props) {
    super(props);
    this.state = {
      supplyName: null,
      supplyTypeOneId: '', //
      supplyTypeOneIndex: null, //
      supplyTypeOneName: null,
      supplyTypeTwoId: '',
      supplyTypeTwoIndex: null,
      supplyTypeTwoName: null,
      packagingTypeId: [], // 选择的打包类型 暂存为数组
      packagingTypes: [], // 供选择的打包类型
      isLimitDate: 1, // 是否限期 1限期 2不限期
      isLimitWeight: 1, // 是否限量 1限量 2不限量
      unitList: [], // 计量单位列表
      weight: null, // 重量 限量时必填
      weightUnit: [], // 重量单位
      isTimeShow: false,
      isTimeType: 'invalidTimeStartStr',
      invalidTimeStartStr: '', // 当限期时 有效结束时间 必填
      invalidTimeEndStr: '', // 当限期时 有效结束时间
      isSubmit: false,
      keyboardHeight: '', // 键盘高度
    };
  }

  componentDidMount() {
    const { treeList, sourceInfoType, supply } = this.props;

    // 如果是新增
    if (sourceInfoType === 'add') {
      const supplyTypeOneId = treeList[0] ? treeList[0].id : '';
      const supplyTypeOneName = treeList[0] ? treeList[0].name : '';
      this.setState({ supplyTypeOneId, supplyTypeOneIndex: 0, supplyTypeOneName });
    }
    // 如果是编辑
    if (sourceInfoType === 'edit') {
      const {
        supplyName,
        supplyTypeOneId,
        supplyTypeOneName,
        supplyTypeTwoId,
        supplyTypeTwoName,
        packagingTypeId,
        invalidTimeStartStr,
        invalidTimeEndStr,
        isLimitDate,
        isLimitWeight,
        weight,
        weightUnit,
      } = supply;
      this.setState(
        {
          supplyName,
          supplyTypeOneId,
          supplyTypeOneName,
          supplyTypeTwoId,
          supplyTypeTwoName,
          packagingTypeId: [+packagingTypeId],
          invalidTimeStartStr: invalidTimeStartStr
            ? Moment(invalidTimeStartStr).format('YYYY/MM/DD HH:mm:ss')
            : null,
          invalidTimeEndStr: invalidTimeEndStr
            ? Moment(invalidTimeEndStr).format('YYYY/MM/DD HH:mm:ss')
            : null,
          isLimitDate,
          isLimitWeight,
          weight,
          weightUnit: [weightUnit],
        },
        () => {
          // 获取包装方式
          this.findPackageTypeByGoodsTypeId(supplyTypeTwoId);
          // 获取计量单位列表
          this.fetchUnitList();
        },
      );
    }

    // 监听键盘
    this.keyboardDidShowListener = Keyboard.addListener(
      'keyboardWillShow',
      this._keyboardDidShow.bind(this),
    );
    this.keyboardDidHideListener = Keyboard.addListener(
      'keyboardWillHide',
      this._keyboardDidHide.bind(this),
    );
  }

  componentWillUnmount() {
    this.keyboardDidShowListener.remove();
    this.keyboardDidHideListener.remove();
  }

  render() {
    const { onChangeModal, sourceInfoType, supply, treeList } = this.props;
    const {
      supplyTypeOneId,
      supplyTypeOneIndex,
      weight,
      supplyName,
      packagingTypes,
      packagingTypeId,
      isLimitDate,
      isLimitWeight,
      unitList,
      weightUnit,
      isTimeShow,
      isTimeType,
      invalidTimeStartStr,
      invalidTimeEndStr,
      isSubmit,
    } = this.state;

    return (
      <Modal
        animationType='slide'
        transparent
        visible
        onRequestClose={() => {
          onChangeModal({ type: 'sourceInfoIsShow', val: false });
          // msg.emit('router: back');
        }}
        onShow={() => {}}
      >
        <TouchableOpacity
          style={styles.mask}
          onPress={() => {
            onChangeModal({ type: 'sourceInfoIsShow', val: false });
            if (!weight) {
              onChangeModal({
                type: 'sourceInfoType',
                val: 'add',
              });
            }
          }}
        />

        <View style={[styles.infoContainer, { marginBottom: Number(this.state.keyboardHeight) }]}>
          <View style={styles.header}>
            <TouchableOpacity
              style={styles.cancel}
              onPress={() => {
                onChangeModal({ type: 'sourceInfoIsShow', val: false });
                if (!weight) {
                  onChangeModal({
                    type: 'sourceInfoType',
                    val: 'add',
                  });
                }
              }}
            >
              <Text style={{ fontSize: px2dp(32), color: fontColorSecDeepGray }}>
                取消
              </Text>
            </TouchableOpacity>
            <Text
              style={{
                fontSize: px2dp(32),
                color: fontColorBlack,
                fontWeight: 'bold',
              }}
            >
              货物信息
            </Text>
            {sourceInfoType === 'edit' && (
              <Submit
                text='确定'
                boxStyle={{
                  width: px2dp(104),
                  height: px2dp(60),
                  borderRadius: px2dp(8),
                  position: 'absolute',
                  right: px2dp(28),
                }}
                disabled={false}
                onClick={() => {
                  this.submit();
                }}
              />
            )}
          </View>

          {/* 类别 */}
          {sourceInfoType === 'add' && (
            <View style={styles.listContainer}>
              <ScrollView
                style={{
                  width: px2dp(300),
                  backgroundColor: mainBgColorLightGray,
                }}
                showsVerticalScrollIndicator={false}
              >
                <View style={styles.leftMenu}>
                  {!!treeList &&
                    treeList.map((item, supplyTypeOneIndex) => {
                      return (
                        <TouchableOpacity
                          style={[
                            styles.leftMenuItem,
                            supplyTypeOneId === item.id
                              ? { backgroundColor: mainBgColorWhite }
                              : {},
                          ]}
                          key={item.id}
                          onPress={() => {
                            this.setState({
                              supplyTypeOneId: item.id,
                              supplyTypeOneIndex,
                              supplyTypeOneName: item.name,
                            });
                          }}
                        >
                          <Text
                            style={[
                              styles.itemtext,
                              supplyTypeOneId === item.id
                                ? { color: fontColorCoffee }
                                : {},
                            ]}
                          >
                            {item.name}
                          </Text>
                        </TouchableOpacity>
                      );
                    })}
                </View>
              </ScrollView>
              {/* 选择二级分类 */}
              <ScrollView
                style={{
                  width: screenWidth - px2dp(300),
                }}
                showsVerticalScrollIndicator={false}
              >
                <View style={styles.rightMenu}>
                  {!!treeList[supplyTypeOneIndex] &&
                    treeList[supplyTypeOneIndex].sons.map((item) => {
                      return (
                        <TouchableOpacity
                          style={styles.rightMenuItem}
                          key={item.id}
                          onPress={() => {
                            this.selectSupplyTypeTwo(item);
                          }}
                        >
                          <Text style={styles.itemtext}>{item.name}</Text>
                        </TouchableOpacity>
                      );
                    })}
                </View>
              </ScrollView>
            </View>
          )}

          {/* 编辑 */}
          {sourceInfoType === 'edit' && (
            <ScrollView showsVerticalScrollIndicator={false}>
              <View style={styles.editContainer}>
                <View style={styles.title}>
                  <View
                    style={{
                      flex: 1,
                      justifyContent: 'center',
                      alignItems: 'center',
                      marginLeft: px2dp(60) * 2,
                    }}
                  >
                    <Text
                      numberOfLines={1}
                      style={{
                        fontSize: px2dp(36),
                        fontWeight: 'bold',
                        color: mainBgColorBlack,
                        marginRight: px2dp(100),
                      }}
                    >
                      {supplyName}
                    </Text>
                  </View>
                  <TouchableOpacity
                    style={[styles.update]}
                    onPress={() => {
                      onChangeModal({
                        type: 'sourceInfoType',
                        val: 'add',
                      });
                    }}
                  >
                    <Image
                      style={[styles.dotImg]}
                      resizeMode='contain'
                      source={iconUpdate}
                    />
                    <Text
                      style={{
                        fontSize: px2dp(28),
                        color: fontColorSecDeepGray,
                      }}
                    >
                      更改
                    </Text>
                  </TouchableOpacity>
                </View>
                <DashLine />
                {/* 包装方式 */}
                <View style={styles.packing}>
                  <Text
                    style={{
                      fontSize: px2dp(28),
                      fontWeight: 'bold',
                      color: mainBgColorBlack,
                    }}
                  >
                    包装方式
                  </Text>
                  <View style={styles.packingSelect}>
                    {!!packagingTypes &&
                      packagingTypes.map((item) => {
                        return (
                          <SelectItem
                            name={item.name}
                            type='packagingTypeId'
                            value={item.id}
                            activeVal={packagingTypeId}
                            maxLength={1}
                            onChange={(type, value) =>
                              this.onChange(type, [value])}
                          />
                        );
                      })}
                  </View>
                </View>

                {/* 是否限期 */}
                <View style={styles.packing}>
                  <View style={styles.itemHeader}>
                    <Text
                      style={{
                        fontSize: px2dp(28),
                        fontWeight: 'bold',
                        color: mainBgColorBlack,
                      }}
                    >
                      是否限期
                      {isLimitDate === 1 && (
                        <Text
                          style={{
                            fontSize: px2dp(28),
                            fontWeight: 'normal',
                            color: !isSubmit ? fontColorSecDeepGray : 'red',
                          }}
                        >
                          (必填、起始日期在结束日期之前)
                        </Text>
                      )}
                    </Text>
                    <Switch
                      trackColor={{
                        false: '#E6E6E5',
                        true: fontColorCoffee,
                      }}
                      value={isLimitDate === 1}
                      onValueChange={(value) => {
                        this.onChange('isLimitDate', isLimitDate === 1 ? 2 : 1);
                        this.setState({
                          invalidTimeStartStr: '',
                          invalidTimeEndStr: '',
                        });
                      }}
                      // disabled={this.state.switchState}
                      testID='one'
                      thumbColor='#fff'
                    />
                  </View>

                  {isLimitDate === 1 && (
                    <View
                      style={{
                        flexDirection: 'row',
                        justifyContent: 'space-between',
                        alignItems: 'center',
                        marginTop: px2dp(24),
                      }}
                    >
                      <TouchableOpacity
                        style={[styles.startAndEndTimeWrap]}
                        onPress={() => {
                          this.setState({
                            isTimeShow: true,
                            isTimeType: 'invalidTimeStartStr',
                          });
                        }}
                        activeOpacity={0.8}
                      >
                        <Text>{invalidTimeStartStr ? Moment(invalidTimeStartStr).format('YYYY/MM/DD') : '必填，起始日期'}</Text>
                      </TouchableOpacity>
                      <View style={styles.timeLine} />
                      <TouchableOpacity
                        style={[styles.startAndEndTimeWrap]}
                        onPress={() => {
                          this.setState({
                            isTimeShow: true,
                            isTimeType: 'invalidTimeEndStr',
                          });
                        }}
                        activeOpacity={0.8}
                      >
                        <Text>{invalidTimeEndStr ? Moment(invalidTimeEndStr).format('YYYY/MM/DD') : '必填，截止日期'}</Text>
                      </TouchableOpacity>
                    </View>
                  )}
                </View>

                {/* 是否限量 */}
                <View style={styles.packing}>
                  <View style={styles.itemHeader}>
                    <Text
                      style={{
                        fontSize: px2dp(28),
                        fontWeight: 'bold',
                        color: mainBgColorBlack,
                      }}
                    >
                      是否限量
                      {' '}
                      {isLimitWeight === 1 && (
                        <Text
                          style={{
                            fontSize: px2dp(28),
                            fontWeight: 'normal',
                            color: !isSubmit ? fontColorSecDeepGray : 'red',
                          }}
                        >
                          (必填、数量和单位)
                        </Text>
                      )}
                    </Text>
                    <Switch
                      trackColor={{
                        false: '#E6E6E5',
                        true: fontColorCoffee,
                      }} // 关闭状态时的边框颜色(iOS)或背景颜色(Android)。
                      value={isLimitWeight === 1}
                      onValueChange={(value) => {
                        // 当开关状态改变了，一定要修改value的值，不然最终无法改变状态
                        this.onChange(
                          'isLimitWeight',
                          isLimitWeight === 1 ? 2 : 1,
                        );
                        this.setState({
                          weight: '',
                          weightUnit: [],
                        });
                      }}
                      // disabled={this.state.switchState}
                      testID='one'
                      thumbColor='#fff'
                    />
                  </View>

                  {isLimitWeight === 1 && (
                    <View style={styles.weightSelect}>
                      <TextInput
                        placeholder='必填，请输入数量'
                        style={[
                          styles.goodsWrapPriceTextInput,
                          { color: fontColorBlack },
                        ]}
                        defaultValue={weight}
                        value={weight}
                        underlineColorAndroid='transparent'
                        onChangeText={(text) => {
                          this.onChangeWeight(text);
                        }}
                        keyboardType={
                          Platform.OS === 'android' ? 'numeric' : 'decimal-pad'
                        }
                        onBlur={() => {}}
                      />
                      <Text style={{ color: fontColorDeepGray }}>
                        {weightUnit}
                      </Text>
                    </View>
                  )}

                  {isLimitWeight === 1 && (
                    <View style={styles.packingSelect}>
                      {!!unitList.length &&
                        unitList.map((item) => {
                          return (
                            <SelectItem
                              name={item.name}
                              type='weightUnit'
                              value={item.name}
                              activeVal={weightUnit}
                              maxLength={1}
                              onChange={(type, value) => {
                                this.onChange(type, [value]);
                              }}
                            />
                          );
                        })}
                    </View>
                  )}
                </View>
              </View>
            </ScrollView>
          )}
          <DateTimePicker
            isVisible={isTimeShow}
            mode='date'
            cancelTextIOS='取消'
            confirmTextIOS='确认'
            headerTextIOS='选取日期'
            locale='zh_CN'
            onConfirm={(val) => {
              this.handleConfirm(val);
            }}
            onCancel={() => {
              this.handleCancel();
            }}
          />
        </View>
      </Modal>
    );
  }

  // 提交
  submit = () => {
    const {
      supplyName,
      supplyTypeOneId,
      supplyTypeOneName,
      supplyTypeTwoId,
      supplyTypeTwoName,
      packagingTypeId,
      packagingTypes,
      isLimitWeight,
      weight,
      weightUnit,
      isLimitDate,
      invalidTimeStartStr,
      invalidTimeEndStr,
    } = this.state;
    let itemType = packagingTypes.find((item) => {
      if (item.id == packagingTypeId.join()) {
        return item;
      }
    });
    if (isLimitDate == 1 && (!invalidTimeStartStr || !invalidTimeEndStr)) {
      this.setState({ isSubmit: true });
      return;
    }
    if (isLimitWeight == 1 && (!weight || !weightUnit.length || weightUnit[0] == undefined)) {
      this.setState({ isSubmit: true });
      return;
    }
    if (
      Moment(invalidTimeStartStr).unix('X') >
      Moment(invalidTimeEndStr).unix('X')
    ) {
      this.setState({ isSubmit: true });
      return;
    }

    const { onChangeModal, onChangeVal } = this.props;
    if (!itemType) {
      msg.emit('app:tip', { text: '请选择包装方式' });
      return;
    }
    let val = {
      supplyName,
      supplyTypeOneId,
      supplyTypeOneName,
      supplyTypeTwoId,
      supplyTypeTwoName,
      packagingType: itemType.name,
      packagingTypeId: packagingTypeId.join(),
      weight,
      weightUnit: weightUnit[0],
      isLimitDate,
      isLimitWeight,
      invalidTimeStartStr,
      invalidTimeEndStr,
    };
    if (weightUnit[0]) {
      val.freightUnit = weightUnit[0];
      // val.lossesUnit = weightUnit[0]
    }
    onChangeVal({
      type: 'supply',
      val
    });
    onChangeModal({ type: 'sourceInfoIsShow', val: false });
    onChangeModal({
      type: 'sourceInfoType',
      val: 'edit',
    });
  };

  handleConfirm = (val) => {
    const { isTimeType, invalidTimeStartStr, invalidTimeEndStr } = this.state;
    if (isTimeType == 'invalidTimeStartStr') {
      this.setState({ invalidTimeStartStr: Moment(val).startOf('day').format('YYYY/MM/DD HH:mm:ss') });
    }
    if (isTimeType == 'invalidTimeEndStr') {
      this.setState({ invalidTimeEndStr: Moment(val).endOf('day').format('YYYY/MM/DD HH:mm:ss') });
    }
    this.setState({ isTimeShow: false });
  };

  handleCancel = (val) => {
    this.setState({ isTimeShow: false });
  };

  // 选择第二个货物类型
  selectSupplyTypeTwo(item) {
    const { onChangeModal, onChangeVal } = this.props;
    const { supplyTypeOneName } = this.state;
    this.setState({ supplyTypeTwoId: item.id });
    this.setState({
      supplyTypeTwoName: item.name,
      supplyName: `${supplyTypeOneName}-${item.name}`,
    });
    onChangeModal({
      type: 'sourceInfoType',
      val: 'edit',
    });
    // 获取包装方式
    this.findPackageTypeByGoodsTypeId(item.id);
    // 获取计量单位列表
    this.fetchUnitList();
  }

  // 获取包装方式
  findPackageTypeByGoodsTypeId = (id) => {
    const { packagingType, packagingTypeId } = this.state;
    findPackageTypeByGoodsTypeId(id).then((res) => {
      if (res.success) {
        this.setState({ packagingTypes: res.data });
        if (res.data.length != 0 && packagingTypeId.length == 0) {
          this.setState({
            packagingTypeId: [res.data[0].id],
          });
        }
      }
    });
  };

  // 获取计量单位列表
  fetchUnitList = () => {
    const { weightUnit } = this.state;
    fetchUnitList({}).then((res) => {
      if (res.success) {
        this.setState({ unitList: res.data });
        if (res.data.length != 0 && !weightUnit) {
          this.setState({
            weightUnit: res.data[0].name,
          });
        }
      }
    });
  };

  _keyboardDidShow(e) {
    this.setState({
      keyboardHeight: e.startCoordinates.height,
    });
  }

  _keyboardDidHide(e) {
    this.setState({
      keyboardHeight: 0,
    });
  }

  // 改变
  onChange = (type, val) => {
    this.setState({ [type]: val });
  };

  // 修改重量
  onChangeWeight = (val) => {
    const { weight } = this.state;
    if (/\D/g.test(val)) {
      const val1 = val.replace(/\D/g, '');
      this.setState({ weight: val1 });
      return;
    }
    this.setState({ weight: val });
  };
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    backgroundColor: mainBgColorLightGray,
    justifyContent: 'center',
  },
  mask: {
    width: screenWidth,
    height: screenHeight,
    backgroundColor: 'rgba(0,0,0,0.2)',
    position: 'absolute',
    left: 0,
    top: 0,
  },
  infoContainer: {
    width: screenWidth,
    maxHeight: px2dp(800),
    backgroundColor: mainBgColorWhite,
    position: 'absolute',
    bottom: 0,
    left: 0,
    borderRadius: px2dp(12),
    overflow: 'hidden',
    zIndex: 10,
  },
  header: {
    width: screenWidth,
    height: px2dp(108),
    justifyContent: 'center',
    alignItems: 'center',
    borderBottomWidth: 1 / PixelRatio.get(),
    borderColor: splitLineColorLightGray,
    paddingHorizontal: px2dp(48),
  },
  cancel: {
    position: 'absolute',
    left: 0,
    top: 0,
    width: 80,
    height: '100%',
    justifyContent: 'center',
    alignItems: 'center',
  },
  listContainer: {
    // paddingVertical: px2dp(16),
    flexDirection: 'row',
  },
  editContainer: {
    padding: px2dp(32),
    paddingBottom: px2dp(100)
  },
  item: {
    width: '100%',
    height: px2dp(92),
    justifyContent: 'center',
    alignItems: 'center',
  },
  title: {
    width: '100%',
    height: px2dp(92),
    justifyContent: 'center',
    alignItems: 'center',
    position: 'relative',
  },
  dotImg: {
    width: px2dp(24),
    height: px2dp(24),
  },
  update: {
    position: 'absolute',
    right: 0,
    flexDirection: 'row',
    alignItems: 'center',
  },
  packing: {
    marginTop: px2dp(48),
  },
  packingSelect: {
    marginTop: px2dp(24),
    flexDirection: 'row',
    flexWrap: 'wrap',
    justifyContent: 'flex-start',
  },
  itemHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  selectItem: {
    width: px2dp(218),
    height: px2dp(72),
    backgroundColor: mainBgColorLightGray,
    borderRadius: px2dp(8),
    justifyContent: 'center',
    alignItems: 'center',
    marginBottom: px2dp(16),
    marginRight: px2dp(10),
  },
  startAndEndTimeWrap: {
    fontSize: px2dp(28),
    height: px2dp(72),
    width: '42%',
    backgroundColor: mainBgColorLightGray,
    alignItems: 'center',
    justifyContent: 'center',
  },
  goodsWrapPriceTextInput: {
    fontSize: px2dp(28),
    height: px2dp(72),
    width: '48%',
    backgroundColor: mainBgColorLightGray,
    flex: 1,
    paddingTop: 0,
    paddingBottom: 0,
  },
  weightSelect: {
    marginTop: px2dp(24),
    paddingHorizontal: px2dp(24),
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    backgroundColor: mainBgColorLightGray,
  },
  itemtext: {
    color: fontColorDeepGray,
    fontSize: px2dp(28),
  },
  leftMenu: {
    backgroundColor: mainBgColorLightGray,
    paddingBottom: px2dp(180),
    width: px2dp(300),
  },
  rightMenu: {
    backgroundColor: mainBgColorWhite,
    paddingBottom: px2dp(180),
    flex: 1,
  },
  leftMenuItem: {
    width: '100%',
    height: px2dp(92),
    justifyContent: 'center',
    alignItems: 'center',
  },
  rightMenuItem: {
    height: px2dp(92),
    justifyContent: 'center',
    alignItems: 'center',
  },
  timeLine: {
    width: px2dp(32),
    height: 1,
    backgroundColor: splitLineColorLightGray,
    marginHorizontal: px2dp(30),
  },
});
